package servlet;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/Venue", "/venue", "/VenueServlet", "/venueServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class VenueServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public VenueServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<VenueModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				getServletContext().getRequestDispatcher("/venueNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			VenueModel query = new VenueModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

			VenueModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("venue", obj);
				getServletContext().getRequestDispatcher("/venueEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			VenueModel query = new VenueModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

			VenueModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("venue", obj);
				getServletContext().getRequestDispatcher("/venueView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			VenueModel obj = new VenueModel();

			// TODO set name here

			GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

			int res = 0;

			try {
				String strName = request.getParameter("name");

				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8");

				obj.setName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("venue", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			VenueModel query = new VenueModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("venueList.jsp");
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		} else if (mode.equalsIgnoreCase("getCascadeDropdowList")){
			response.setContentType("text/xml; charset=UTF-8");
			String idPlace=request.getParameter("idParent");
			
			try{
			List<VenueModel> list = CacheUtil.getVenueList(Integer.parseInt(idPlace));
			List<String> listVenue = new ArrayList<String>();
			List<String> listVenueId = new ArrayList<String>();
			for(int i=0;i<list.size();i++)
			{
				listVenue.add(i, list.get(i).getName());
				listVenueId.add(i, list.get(i).getIdToString());
			}
			PrintWriter out = response.getWriter();
			
			String resultXML = CommonUtil.createAjaxResultXML("venue", listVenue, listVenueId);
			out.println(resultXML);
			}
			catch(Exception e)
			{}
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			VenueModel obj = new VenueModel();

			String id_place = request.getParameter("id_place");
            if (id_place != null && !id_place.isEmpty()) {
			    obj.setIdPlace(Integer.parseInt(id_place));
            }

String id_type = request.getParameter("id_type");
            if (id_type != null && !id_type.isEmpty()) {
			    obj.setIdType(Integer.parseInt(id_type));
            }

String name = request.getParameter("name");
			obj.setName(name);

String code = request.getParameter("code");
			obj.setCode(code);

//String description = request.getParameter("description");
//			obj.setDescription(description);

//String id_company = request.getParameter("id_company");
//            if (id_company != null && !id_company.isEmpty()) {
//			    obj.setIdCompany(Integer.parseInt(id_company));
//            }
//
//String abb_name = request.getParameter("abb_name");
//			obj.setAbbName(abb_name);
//
//String short_name = request.getParameter("short_name");
//			obj.setShortName(short_name);
//
//String foreign_name = request.getParameter("foreign_name");
//			obj.setForeignName(foreign_name);

String address = request.getParameter("address");
			obj.setAddress(address);

//String telephone = request.getParameter("telephone");
//			obj.setTelephone(telephone);

String fax = request.getParameter("fax");
			obj.setFax(fax);

String capacity = request.getParameter("capacity");
            if (capacity != null && !capacity.isEmpty()) {
			    obj.setCapacity(Integer.parseInt(capacity));
            }

String contact_person_1 = request.getParameter("contact_person_1");
			obj.setContactPerson1(contact_person_1);

String contact_phone_1 = request.getParameter("contact_phone_1");
			obj.setContactPhone1(contact_phone_1);

String contact_mobile_1 = request.getParameter("contact_mobile_1");
			obj.setContactMobile1(contact_mobile_1);

String contact_email_1 = request.getParameter("contact_email_1");
			obj.setContactEmail1(contact_email_1);

String contact_person_2 = request.getParameter("contact_person_2");
			obj.setContactPerson2(contact_person_2);

String contact_phone_2 = request.getParameter("contact_phone_2");
			obj.setContactPhone2(contact_phone_2);

String contact_mobile_2 = request.getParameter("contact_mobile_2");
			obj.setContactMobile2(contact_mobile_2);

String contact_email_2 = request.getParameter("contact_email_2");
			obj.setContactEmail2(contact_email_2);

String remark = request.getParameter("remark");
			obj.setRemark(remark);

//String map_path = request.getParameter("map_path");
//			obj.setMapPath(map_path);
//
//String status = request.getParameter("status");
//            if (status != null && !status.isEmpty()) {
//			    obj.setStatus(Integer.parseInt(status));
//            }
//
//String is_draft = request.getParameter("is_draft");
//			obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//					|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//            if (notification != null && !notification.isEmpty()) {
//			    obj.setNotification(Integer.parseInt(notification));
//            }
			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, redirect to somewhere
					response.sendRedirect("venueNew.jsp?idPlace=" + obj.getIdPlaceToString());
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("venue", obj);
				getServletContext().getRequestDispatcher("/venueInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			VenueModel query = new VenueModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

			VenueModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				String id_place = request.getParameter("id_place");
	            if (id_place != null && !id_place.isEmpty()) {
				    obj.setIdPlace(Integer.parseInt(id_place));
	            }

	String id_type = request.getParameter("id_type");
	            if (id_type != null && !id_type.isEmpty()) {
				    obj.setIdType(Integer.parseInt(id_type));
	            }

	String name = request.getParameter("name");
				obj.setName(name);

	String code = request.getParameter("code");
				obj.setCode(code);

	//String description = request.getParameter("description");
//				obj.setDescription(description);

	//String id_company = request.getParameter("id_company");
//	            if (id_company != null && !id_company.isEmpty()) {
//				    obj.setIdCompany(Integer.parseInt(id_company));
//	            }
	//
	//String abb_name = request.getParameter("abb_name");
//				obj.setAbbName(abb_name);
	//
	//String short_name = request.getParameter("short_name");
//				obj.setShortName(short_name);
	//
	//String foreign_name = request.getParameter("foreign_name");
//				obj.setForeignName(foreign_name);

	String address = request.getParameter("address");
				obj.setAddress(address);

	//String telephone = request.getParameter("telephone");
//				obj.setTelephone(telephone);

	String fax = request.getParameter("fax");
				obj.setFax(fax);

	String capacity = request.getParameter("capacity");
	            if (capacity != null && !capacity.isEmpty()) {
				    obj.setCapacity(Integer.parseInt(capacity));
	            }

	String contact_person_1 = request.getParameter("contact_person_1");
				obj.setContactPerson1(contact_person_1);

	String contact_phone_1 = request.getParameter("contact_phone_1");
				obj.setContactPhone1(contact_phone_1);

	String contact_mobile_1 = request.getParameter("contact_mobile_1");
				obj.setContactMobile1(contact_mobile_1);

	String contact_email_1 = request.getParameter("contact_email_1");
				obj.setContactEmail1(contact_email_1);

	String contact_person_2 = request.getParameter("contact_person_2");
				obj.setContactPerson2(contact_person_2);

	String contact_phone_2 = request.getParameter("contact_phone_2");
				obj.setContactPhone2(contact_phone_2);

	String contact_mobile_2 = request.getParameter("contact_mobile_2");
				obj.setContactMobile2(contact_mobile_2);

	String contact_email_2 = request.getParameter("contact_email_2");
				obj.setContactEmail2(contact_email_2);

	String remark = request.getParameter("remark");
				obj.setRemark(remark);

	//String map_path = request.getParameter("map_path");
//				obj.setMapPath(map_path);
	//
	//String status = request.getParameter("status");
//	            if (status != null && !status.isEmpty()) {
//				    obj.setStatus(Integer.parseInt(status));
//	            }
	//
	//String is_draft = request.getParameter("is_draft");
//				obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//						|| is_draft.equalsIgnoreCase("1"));
	//
	//String notification = request.getParameter("notification");
//	            if (notification != null && !notification.isEmpty()) {
//				    obj.setNotification(Integer.parseInt(notification));
//	            }

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success						
						response.sendRedirect("venueList.jsp?idPlace=" + obj.getIdPlaceToString());
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("venue", obj);
					getServletContext().getRequestDispatcher("/venueList.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			VenueModel obj = new VenueModel();

			// TODO set name here

			GenericDal<VenueModel, VenueModelExt> dal = new GenericDal<VenueModel, VenueModelExt>(new VenueModel());

			int res = 0;

			try {
				String strName = request.getParameter("name");

				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8");

				obj.setName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("venue", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}